package ReflectionTest;

class User {
    public String name;
    private int age;

    public User() {
        System.out.println("Person() called");
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }
}

public class RuntimeClassTest {
    public static void main(String[] args) {
        try {
            getInstanceOfClass();
            System.out.println(getInstanceOfClass("ReflectionTest.User"));
            System.out.println(getInstanceOfClass("java.util.Date"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取类的实例
    public static void getInstanceOfClass() throws InstantiationException, IllegalAccessException {
        Class<User> userClass = User.class;
        System.out.println(userClass.newInstance());
    }

    // 根据类名动态获取类的实例
    public static Object getInstanceOfClass(String className)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        Class clazz = Class.forName(className);
        return clazz.newInstance();
    }

}
